/*
 * Created on 07.10.2005
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package de.fmannan.addbook.editor.util;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;

import de.fmannan.addbook.editor.types.TypesUtil;


public class DoubleUtil {

    private static final NumberFormat standardFormat = NumberFormat.getInstance();
    private static final String INVALID_STRING_DISPLAY = "";

    private DoubleUtil() {
        // Util is not instantiable.
    }

    public static String formatDouble(double value)
    {
        return TypesUtil.isValidDouble(value) ? standardFormat.format(value) : INVALID_STRING_DISPLAY;
    }

    public static double parseDouble(String numberString) throws ParseException 
    {        
        String trimmedString = numberString.trim();        
        return (trimmedString != null && ! trimmedString.equals(INVALID_STRING_DISPLAY)) ? parseDoubleOnly(trimmedString) : TypesUtil.getInvalidDouble();
    }

    private static double parseDoubleOnly(String trimmedString) throws ParseException {
        // Accept double values only. Raise exception if necessary.
        // TODO: This looks somewhat clumsy. Is there a better way to achieve the same effect?
        standardFormat.setParseIntegerOnly(false);
        ParsePosition position = new ParsePosition(0);
        Number parsedNumber = standardFormat.parse(trimmedString, position);
        int firstUnusedPosition = position.getIndex();
        if ( firstUnusedPosition != trimmedString.length() ) {
            throw new ParseException("Bitte geben Sie eine Zahl ein!", firstUnusedPosition);
        }
        
        return parsedNumber.doubleValue();
    }
    
    
    public static String formatXMLDouble(double value)
    {
    	String normalizedString = TypesUtil.isValidDouble(value) ? Double.toString(value) : INVALID_STRING_DISPLAY;
        return normalizedString.replace('.', ',');
    }

    public static double parseXMLDouble(String numberString) throws ParseException 
    {        
    	String normalizedString = numberString.replace(',','.');
    	return (normalizedString != null && !normalizedString.equals(INVALID_STRING_DISPLAY)) ? Double.parseDouble(normalizedString) : TypesUtil.getInvalidDouble();
    }

}
